import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom'
import { useForm } from '@mantine/form'
import { useMutation } from 'react-query'
import { GLOBAL_PLACEHOLDER } from '@/configs';
import { useLocalStorage } from '@mantine/hooks';
import { TextInput, Button, Checkbox } from '@mantine/core'
import { IconLockSquareRounded, IconUserSquareRounded } from '@tabler/icons-react'
import { login } from '@/apis/user';
import { useToastStore } from '@/store'
import { IUserInfo } from '@/apis/user/model';
import { Bcrypt } from '@/utils/bcrypt';


export default function LoginForm() {
  const navigate = useNavigate();
  const [remember, setRemember] = useState(false);
  const [userInfo, setUserinfo] = useLocalStorage<IUserInfo>({key: 'userinfo'});
  const showToast = useToastStore(state => state.showToast);
  const loginCache = getLoginCache();

  const mutation = useMutation({
    mutationFn: login,
  });

  const form = useForm({
    mode: 'controlled',
    initialValues: {
      username: loginCache?.username || '',
      password: loginCache?.password || ''
    },
    validate: {
      username: (value) => value ? null : '请输入用户名',
      password: (value) => value ? null : '请输入密码'
    },
  });

  useEffect(() => {
    if (userInfo?.cache) {
      form.setValues(userInfo.cache);
    }
  }, [userInfo])

  function getLoginCache() {
    console.log('cache ', userInfo)
    return  userInfo?.cache;
  }

  async function onLogin() {
    const valid = form.validate();
    if (valid.hasErrors) return
    const loginData = form.getValues();
    // loginData.password  = await Bcrypt.hash(loginData.password);
    const { code, data } = await mutation.mutateAsync(loginData);
    if (code === 200) {
      showToast({
        title: '提示',
        descripion: "登录成功!",
        type: 'success'
      })
      setUserinfo(data);

      //todo: 记住密码
      if (remember) {
        setUserinfo({
          ...data,
          cache: loginData
        });
      }

      navigate('/');
    }
  }

  return (
    <form className='mt-12' >
      <TextInput 
      size='lg' 
      leftSection={<IconUserSquareRounded />}
      placeholder={GLOBAL_PLACEHOLDER.USERNAME} 
      {...form.getInputProps('username')} />

      <TextInput 
      size='lg' 
      type='password'
      leftSection={<IconLockSquareRounded />}
      placeholder={GLOBAL_PLACEHOLDER.PASSWORD} 
      className='mt-6' {...form.getInputProps('password')} />

      <div className='mt-6'>
        <div className='flex items-center justify-between'>
          <Checkbox size='md' label="记住密码" onChange={(e) => setRemember(e.target.checked)} />
          <a href="">忘记密码?</a>
        </div>
      </div>

      <Button loading={mutation.isLoading} className='mt-8' size='lg' fullWidth onClick={onLogin} >登录</Button>
    </form>
  )
}